import fs from "fs";
import express from "express";
import { createServer as createViteServer } from "vite";

const isProd = process.env.NODE_ENV === "production"; // 判断是否为生产环境
const isDev = process.env.NODE_ENV === "development"; // 判断是否为开发环境
console.log("isProd", isProd, "isDev", isDev); // 打印当前环境

async function createServer() {
  // 创建一个Vite服务器
  const app = express();
  let vite;

  if (isDev) {
    vite = await createViteServer({
      server: { middlewareMode: true }, // 中间件模式
      appType: "custom", // 自定义应用类型
    });
    app.use(vite.middlewares); // 使用Vite中间件
  } else {
    app.use(express.static("dist/client")); // 静态文件服务
  }

  app.use(/\/.*/, async (req, res) => {
    let template, render, ssrManifest;
    if (isDev) {
      template = fs.readFileSync("./index.html", "utf-8");
      template = await vite.transformIndexHtml(req.originalUrl, template); // 转换HTML模板
      const server = await vite.ssrLoadModule("./src/server.js"); // 动态导入服务器端渲染模块
      render = server.render; // 获取渲染函数
    } else {
      template = fs.readFileSync("./dist/client/index.html", "utf-8"); // 读取生产环境的HTML模板
      render = (await import("./dist/server/server.js")).render; // 动态导入服务器端渲染模块
      // ssrManifest = await import("./dist/client/ssr-manifest.json"); // 读取SSR清单
    }

    const appHtml = await render(req.originalUrl, ssrManifest);
    template = template.replace(`<!--ssr-outlet-->`, appHtml); // 替换占位符
    // console.log("n ---------------\n", template, "\n ---------------");
    res.setHeader("Content-Type", "text/html");
    res.status(200).send(template); // 发送响应
  });

  // 设置静态文件缓存
  app.use(
    "/assets",
    express.static("dist/client/assets", {
      maxAge: "1month",
      immutable: true,
    })
  );

  app.listen(3000, () => {
    console.log("Server is running at http://localhost:3000");
  });
}

createServer();
